package com.sxkiler.demo.test.common.config;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.druid.filter.config.ConfigTools;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.Serializable;

public class MysqlJdbcConfig implements BaseDbConfig,Serializable {

    private static final long serialVersionUID = -3786681729815064500L;
    private static Logger logger = LoggerFactory.getLogger(MysqlJdbcConfig.class);
    private String name;
    private String url;
    private String username;
    private String password;
    private String publicKey;

    public MysqlJdbcConfig(){}
    public MysqlJdbcConfig(String name){
        this.name = name;
    }

    @Override
    public boolean isValid() {
        if(ObjectUtil.isAllNotEmpty(name,url,username,password)){
            return true;
        }
        return false;
    }

    @Override
    public DBType getDBType(){
        return DBType.MYSQL;
    }
    @Override
    public String getName() {
        return name;
    }
    @Override
    public void setName(String name) {
        this.name = name;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getPublicKey() {
        return publicKey;
    }

    public void setPublicKey(String publicKey) {
        this.publicKey = publicKey;
    }

    public String getSchemaName(){
        if(StrUtil.isNotEmpty(url)){
            String temp = url.replace("jdbc:mysql://","");
            return temp.substring(temp.indexOf("/")+1,temp.indexOf("?"));
        }
        return null;
    }
    public String getPlainPassword()  {
        if(StrUtil.isNotEmpty(this.getPublicKey())){
            try{
                return ConfigTools.decrypt(this.getPublicKey(),this.getPassword());
            }catch (Exception e){
                logger.error("解密失败,{}",e.getMessage(),e);
                return this.password;
            }
        }else{
            return this.password;
        }
    }
}
